package com.zzxx.wechat.demo;

import org.apache.http.HttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

public class IgnoreSSLExample {

    public static void main(String[] args) {
        try {
            // 创建一个信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
            };

            // 初始化SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // 使用自定义的SSLContext构建HttpClient
            try (CloseableHttpClient client = HttpClients.custom()

                    .setSSLContext(sslContext)
                    .build()) {

                HttpGet request = new HttpGet("https://arcteryx.com/us/en/shop/X000009141");
                request.setHeader("User-Agent", "Mozilla/5.0");

                try (CloseableHttpResponse response = client.execute(request)) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    System.out.println("Response Status Code: " + statusCode);

                    if (statusCode == 200) {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            String html = EntityUtils.toString(entity);
                            System.out.println("HTML Content Length: " + html.length());
                            System.out.println(html.substring(0, Math.min(500, html.length())) + "...");
                        }
                    } else {
                        // 处理非200状态码的情况
                    }
                }
            }
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
